package com.orivon.mob.hook.helper;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;

import java.util.Random;

import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XC_MethodReplacement;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

/**
 * Created by Eenie on 2016/2/23.
 * Email:472279981@qq.com
 */
public class HookManager implements IXposedHookLoadPackage, IXposedHookZygoteInit {

    private int diceCount = 0;
    private Context mContext;
    private Context HookContext;
    private String cName = "com.tencent.mm.sdk.platformtools.ba";
    private String fName = "pU";
    @Override
    public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable {
        if (loadPackageParam.packageName.equals("com.tencent.mm")) {
            hookAndGetContext("com.tencent.mm.ui.MMFragmentActivity", loadPackageParam, "onCreate");
            findAndHookMethod(cName, loadPackageParam, fName);
        }
    }

    @Override
    public void initZygote(StartupParam startupParam) throws Throwable {

    }


    private void findAndHookMethod(String className,
                                   final XC_LoadPackage.LoadPackageParam lpparam,
                                   String methodName) {
        XposedHelpers.findAndHookMethod(className,
                lpparam.classLoader,
                methodName,
                int.class,
                new XC_MethodReplacement() {
                    @Override
                    protected Object replaceHookedMethod(XC_MethodHook.MethodHookParam param) throws Throwable {
                        Integer gameType = (Integer) param.args[0];
                        switch (gameType) {
                            case 5: // 摇骰子
                                Uri diceUri = Uri.parse("content://com.orivon.mob.hook.mm/" + MyDatabaseHelpser.TABLE_NAME);
                                Cursor diceCursor = mContext.getContentResolver().query(diceUri, new String[]{MyDatabaseHelpser.TABLE_NAME}, null, null, null);
                                if (diceCursor != null && diceCursor.moveToLast()) {
                                    diceCount = diceCursor.getInt(diceCursor.getColumnIndex("dice_num"));
                                    mContext.getContentResolver().delete(diceUri, null, new String[]{diceCursor.getString(0)});
                                } else {
                                    Toast.makeText(mContext, "微骰队列中没有数据了", Toast.LENGTH_SHORT).show();
                                    diceCount = new Random(System.currentTimeMillis()).nextInt(gameType + 0 + 1) + 0;
                                }
                                break;
                            case 2: // 猜拳
//                                Uri morraUri = Uri.parse("content://com.example.hookdemo.provider/wx_plugs_setting");
//                                Cursor morraCursor = mContext.getContentResolver().query(morraUri, null, null, null, null);
//                                if (morraCursor != null) {
//                                    diceCount = morraCursor.getInt(morraCursor.getColumnIndex("morra_num"));
//                                    XposedBridge.log("查询猜拳数为:" + diceCount);
//                                }
                                break;

                        }
                        return diceCount;
                    }
                });
    }


    private void hookAndGetContext(String className, final XC_LoadPackage.LoadPackageParam lpparam, String methodName) {
        XposedHelpers.findAndHookMethod(className, lpparam.classLoader, methodName, Bundle.class, new XC_MethodHook() {
            @Override
            protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                // Hook函数之前执行的代码
                if (mContext == null) {
                    mContext = (Context) param.thisObject;
//                    XposedBridge.log("获取到了微信Context");
                    getVersion(lpparam);
                }
            }

            @Override
            protected void afterHookedMethod(final MethodHookParam param) throws Throwable {
            }
        });
    }


    public String getVersion(XC_LoadPackage.LoadPackageParam loadPackageParam) {
        try {
            String[] ver = ((Context) XposedHelpers.callMethod(XposedHelpers.callStaticMethod(XposedHelpers.findClass("android.app.ActivityThread", null), "currentActivityThread", new Object[0]), "getSystemContext", new Object[0])).getPackageManager().getPackageInfo(loadPackageParam.packageName, 0).versionName.split("_");
            XposedBridge.log("wechat version->" + ver[0].substring(0, ver[0].lastIndexOf(".")));

            switch (ver[0].substring(0, ver[0].lastIndexOf("."))) {

                case "6.3.11":
                    cName = "com.tencent.mm.sdk.platformtools.ay";
                    fName = "pu";
                    break;
                case "6.3.9":
                    cName = "com.tencent.mm.sdk.platformtools.bb";
                    fName = "pu";
                    break;
                case "6.3.8":
                    cName = "com.tencent.mm.sdk.platformtools.bc";
                    fName = "oZ";
                    break;
//                case "6.3.15":
//                    cName = "com.tencent.mm.sdk.platformtools.ba";
//                    fName = "pU";
//                    break;
                default:
                    Uri diceUri = Uri.parse("content://com.orivon.mob.hook.mm/" + MyDatabaseHelpser.TABLE_NAME);
                    Cursor cursor = mContext.getContentResolver().query(diceUri, new String[]{"ver"}, "ver_name=?", new String[]{ver[0].substring(0, ver[0].lastIndexOf("."))}, null);

                    if (cursor != null && cursor.moveToNext()) {
                        cName = cursor.getString(2);
                        fName = cursor.getString(3);
                        XposedBridge.log("version found in database " +cursor.getString(1));
                    } else {
                        Toast.makeText(mContext, "微骰暂时不支持微信" + ver + "\n请更新支持版本信息或者联系QQ：472279981解决", Toast.LENGTH_LONG).show();
                    }
                    break;
            }


            return ver[0];
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "0.0.0";
    }


}
